package com.etime.shyauth.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.etime.shyauth.config.BaseMessage;
import com.etime.shyauth.config.ListMessage;
import com.etime.shyauth.config.PageMessage;
import com.etime.shyauth.config.PojoMessage;
import com.etime.shyauth.dto.PassDto;
import com.etime.shyauth.dto.SysUserRoleDto;
import com.etime.shyauth.pojo.SysUser;
import com.etime.shyauth.services.interfaces.SysUserRoleService;
import com.etime.shyauth.services.interfaces.SysUserService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户管理controller层
 */
@Api(tags = "用户管理数据接口")
@Controller
@ResponseBody
@RequestMapping("/sys/user")
public class SysUserController {

    @Autowired
    private SysUserService service;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @ApiOperation("增加用户")
    @ApiImplicitParam("1、从后台添加的用户，只需要添加用户的用户名（username），密码（userpwd），" +
            "用户姓名（usertruename);联系电话(userphone)\n" +
            "2、从小程序注册,需要添加属性：nickname,openid,unionid,code,从属销售人员id：saleuserid")
    @PostMapping("/insert")
    public BaseMessage insertSysUser(SysUser user) {
        BaseMessage msg = new BaseMessage ();
        int rtn = service.insertSysUser (user);
        msg.setCode (rtn);
        if (rtn > 0) {
            msg.setMsg ("增加用户成功");
        } else {
            msg.setMsg ("增加用户失败");
        }
        return msg;
    }

    @ApiOperation("根据id修改用户")
    @ApiImplicitParam("更新条件：userid；调用方法时，只需要给需要更新的属性进行赋值。")
    @PostMapping("/update")
    public BaseMessage updateSysUser(SysUser user) {
        BaseMessage msg = new BaseMessage ();
        int rtn = service.updateSysUser (user);
        msg.setCode (rtn);
        if (rtn > 0) {
            msg.setMsg ("修改用户成功");
        } else {
            msg.setMsg ("修改用户失败");
        }
        return msg;
    }

    @ApiOperation("根据条件查询用户列表")
    @ApiImplicitParam("支持查询条件：" +
            "用户名：username," +
            "用户状态：userstate（0：不可用；1：可用）," +
            "电话：userphone," +
            "是否教师：isteacher（0：否；1：是）," +
            "是否销售：issaler（0：否；1：是）")
    @GetMapping("/list")
    public ListMessage<SysUser> selectUserList(SysUser user) {
        ListMessage<SysUser> msg = new ListMessage<> ();
        List<SysUser> list = service.selectUserList (user);
        if (list != null) {
            msg.setCode (1);
            msg.setDatalist (list);
        } else {
            msg.setCode (0);
            msg.setMsg ("没有符合要求的记录");
        }
        return msg;
    }

    @ApiOperation("分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "支持查询条件：" +
                    "用户名：username," +
                    "用户状态：userstate（0：不可用；1：可用）," +
                    "电话：userphone," +
                    "是否教师：isteacher（0：否；1：是）," +
                    "是否销售：issaler（0：否；1：是）"),
            @ApiImplicitParam(name = "pagenum", value = "当前第几页"),
            @ApiImplicitParam(name = "pagesize", value = "每页多少行")
    })
    @GetMapping("/page")
    public PageMessage<SysUser> selectUserByPage(SysUser user, Long pagenum, Long pagesize) {
        PageMessage<SysUser> msg = new PageMessage<> ();
        Page<SysUser> data = service.selectUserByPage (user, pagenum, pagesize);
        if (data != null) {
            msg.setCode (1);
            msg.setPagedata (data);
        } else {
            msg.setCode (0);
            msg.setMsg ("查询失败");
        }
        return msg;
    }

    @ApiOperation("根据id查询一条用户详细信息")
    @ApiImplicitParam("用户id")
    @GetMapping("/get/{userid}")
    public PojoMessage<SysUser> selectUserById(@PathVariable("userid") int userid) {
        SysUser user = service.selectUserById (userid);
        PojoMessage<SysUser> msg = new PojoMessage<> ();
        if (user != null) {
            msg.setCode (1);
            msg.setData (user);
        } else {
            msg.setCode (0);
            msg.setMsg ("没有指定的用户");
        }
        return msg;
    }

    @ApiOperation("给用户分配角色。一个用户可以分配多个角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userid", value = "用户id"),
            @ApiImplicitParam(name = "roleids", value = "用户所具有的角色id列表(数组)")
    })
    @PostMapping("/saverole/{userid}")
    public BaseMessage saveUserRole(@PathVariable("userid") Integer userid, @RequestParam List<Integer> roleids) {
        BaseMessage msg = new BaseMessage ();
        try {
            int rtn = sysUserRoleService.insertSysUserRole (userid, roleids);
            msg.setCode (rtn);
        } catch (Exception e) {
            msg.setCode (0);
            msg.setMsg (e.getMessage ());
            e.printStackTrace ();
        }
        return msg;
    }

    @ApiOperation("根据用户id获取该用户所具有的角色列表。" +
            "（全部角色都查询出来，本功能主要用于用户角色分配的页面初始化）")
    @ApiImplicitParam("用户id")
    @GetMapping("/getrole/{userid}")
    @ApiResponse(code = 200, message = "urid=null，表示该用户没有此角色")
    public ListMessage<SysUserRoleDto> selectSysUserRoleList(@PathVariable("userid") Integer userid) {
        ListMessage<SysUserRoleDto> msg = new ListMessage<> ();
        List<SysUserRoleDto> list = sysUserRoleService.selectSysUserRoleDtoList (userid);
        if (list != null) {
            msg.setCode (1);
            msg.setDatalist (list);
        } else {
            msg.setCode (0);
            msg.setMsg ("没有查询到数据");
        }
        return msg;
    }


    @ApiOperation("验证用户名是否存在;code=0:不存在；code=1：存在")
    @ApiImplicitParam("用户名")
    @GetMapping("/check/{username}")
    public BaseMessage checkusername(@PathVariable("username") String username) {
        BaseMessage msg = new BaseMessage ();
        SysUser user = new SysUser ();
        user.setUsername (username);
        List<SysUser> list = service.selectUserList (user);
        if (list != null && list.size () > 0) {
            msg.setCode (1);
            msg.setMsg ("用户名已存在");
        } else {
            msg.setCode (0);
            msg.setMsg ("用户名不存在，可以使用");
        }
        return msg;
    }

    // wb
    @ApiOperation("后台-用戶修改自己的密码")
    @PostMapping("/upUserPass")
    public BaseMessage updateUserPass(PassDto dto) {
        BaseMessage msg = new BaseMessage();
        int rtn = service.updateUserPass(dto);
        if (rtn > 0) {
            msg.setCode(rtn);
            msg.setMsg("修改密码成功");
        } else if (rtn == -1) {
            msg.setMsg("您输入的旧密码不正确！");
        } else {
            msg.setMsg("修改密码失败！");
        }
        return msg;
    }
}
